package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result queryById(Long id) {
//        return queryWithPassThrough(id);
//        return  queryWithMutex(id);
        return  queryWithLogicalExpire(id);
    }
    private final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    private Result queryWithLogicalExpire(Long id) {
        //先从redis查
        String shopJson = redisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        if(StrUtil.isBlank(shopJson)){

            return Result.fail("店铺不存在");
        }
        //命中判读那缓存是否过期
        String jsonStr = redisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        RedisData redisData = JSONUtil.toBean(jsonStr, RedisData.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class);
        if(expireTime.isAfter(LocalDateTime.now())){
            //未过期直接返回
            return Result.ok(shop);
        }
        //过期则缓存重建
        //缓存重建首先获取锁
        String lockKey=RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if(isLock){
//             jsonStr = redisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
//             redisData = JSONUtil.toBean(jsonStr, RedisData.class);
//             expireTime = redisData.getExpireTime();
//             data = (JSONObject) redisData.getData();
//             shop = JSONUtil.toBean(data, Shop.class);
//            if(expireTime.isAfter(LocalDateTime.now())){
//                //未过期直接返回
//                return Result.ok(shop);
//            }
            //开启线程去处理
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    this.saveShop2Redis(id,20l);
                }
                catch (Exception e){
                    e.printStackTrace();
                }
                finally {
                    unlock(lockKey);
                }

            });
        }
        //获取失败了 返回旧数据

        return Result.ok(shop);
    }
    private Result queryWithMutex(Long id) {
        //先从redis查
        String shopJson = redisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        if(StrUtil.isNotBlank(shopJson)){
            Shop cacheShop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(cacheShop);
        }
        String lockKey="lock:shop:"+id;
        Shop shop = null;
        try {
            boolean isLock = tryLock(lockKey);
            if(!isLock){
                Thread.sleep(50);
                return queryWithMutex(id);
            }

            //没用从数据库查
            //模拟延迟
            Thread.sleep(200);
            shop = getById(id);
            if(shop == null){
                redisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "",2l, TimeUnit.MINUTES);
                return Result.fail("店铺不存在");
            }
            //写入缓冲
            String jsonStr = JSONUtil.toJsonStr(shop);
            redisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, jsonStr,30L, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            unlock(lockKey);//要考虑出现异常也要释放锁，否则就是死锁了
        }

        return Result.ok(shop);
    }
    private Result queryWithPassThrough(Long id) {
        //先从redis查
        String shopJson = redisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
        if(StrUtil.isNotBlank(shopJson)){
            Shop cacheShop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(cacheShop);
        }
        if(shopJson!=null){
            return Result.fail("店铺不存在");
        }

        //没用从数据库查
        Shop shop = getById(id);
        if(shop == null){
            redisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "",2l, TimeUnit.MINUTES);
            return Result.fail("店铺不存在");
        }
        //写入缓冲
        String jsonStr = JSONUtil.toJsonStr(shop);
        redisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, jsonStr,30L, TimeUnit.MINUTES);

        return Result.ok(shop);
    }
    public   void saveShop2Redis(Long id,Long expireSecond){
        Shop shop = getById(id);
        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSecond));
        redisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
    }

    private boolean tryLock(String key){
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    private void unlock(String key){
        redisTemplate.delete(key);
    }


    @Override
    public Result updateAndCache(Shop shop) {
        //更新数据库
        Long shopId = shop.getId();
        if(shopId == null){
            return Result.fail("店铺id不能为空");
        }
        updateById(shop);
        //删除缓存
        redisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + shopId);

        return Result.ok();
    }
}
